cmake_policy(SET CMP0140 NEW)
function(UseDebugLibraries_check tgt udl_expect_debug udl_expect_release)
  set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/${tgt}.vcxproj")
  if(NOT EXISTS "${vcProjectFile}")
    set(RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj does not exist.")
    return()
  endif()

  set(have_udl_debug 0)
  set(have_udl_release 0)
  set(inConfig "")

  file(STRINGS "${vcProjectFile}" lines)
  foreach(line IN LISTS lines)
    if(line MATCHES [[^ *<PropertyGroup Condition="'\$\(Configuration\)\|\$\(Platform\)'=='([^"|]+)\|[^"]+" Label="Configuration">.*$]])
      string(TOLOWER "${CMAKE_MATCH_1}" inConfig)
    elseif(inConfig)
      if(line MATCHES "^ *</PropertyGroup>.*$")
        set(inConfig "")
      elseif(line MATCHES "^ *<UseDebugLibraries>([^<>]+)</UseDebugLibraries>")
        set(udl_actual "${CMAKE_MATCH_1}")
        set(have_udl_${inConfig} 1)
        if (NOT "${udl_expect_${inConfig}}" STREQUAL "")
          if(NOT "${udl_actual}" STREQUAL "${udl_expect_${inConfig}}")
            string(APPEND RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj has ${inConfig} UseDebugLibraries '${udl_actual}', not '${udl_expect_${inConfig}}'.\n")
          endif()
        else()
          string(APPEND RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj has ${inConfig} UseDebugLibraries '${udl_actual}', but should not have one.\n")
        endif()
        unset(udl_actual)
      endif()
    endif()
  endforeach()

  if(NOT have_udl_debug AND NOT "${udl_expect_debug}" STREQUAL "")
    string(APPEND RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj does not have a debug UseDebugLibraries field, but should have one.\n")
  endif()
  if(NOT have_udl_release AND NOT "${udl_expect_release}" STREQUAL "")
    string(APPEND RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj does not have a release UseDebugLibraries field, but should have one.\n")
  endif()
  return(PROPAGATE RunCMake_TEST_FAILED)
endfunction()
